package com.fearless.test20210501;

/*

        读写锁

 */


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockTest {

    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 0; i <5 ; i++) {
            final int temp=i;
            new Thread(()->{
                myCache.put(String.valueOf(temp),"嗯嗯");
            },String.valueOf(i)).start();

        }

        for (int i = 0; i <5 ; i++) {
            final  int temp=i;
            new Thread(()->{
                myCache.get(String.valueOf(temp));
            },String.valueOf(i)).start();

        }



    }


}

/*
    自定义一个缓存
 */
class MyCache{


    private volatile Map<String,String> map=new HashMap<>();

    //存，写
    public void put(String key,String value){
        System.out.println(Thread.currentThread().getName()+"写入"+key);
        map.put(key,value);
        System.out.println(Thread.currentThread().getName()+"写入完毕");
    }

    //取，读
    public void get(String key){
        System.out.println(Thread.currentThread().getName()+"读取"+key);
        String s = map.get(key);
        System.out.println(Thread.currentThread().getName()+"成功取出");
    }


}


/*
    加入读写锁的自定义缓存
 */
class MyCacheLock{

     private ReadWriteLock readWriteLock=new ReentrantReadWriteLock();//读写锁

    private volatile Map<String,String> map=new HashMap<>();

    //存，写。写入的时候只希望同时只有一个线程在写
    public void put(String key,String value){
        readWriteLock.writeLock().lock();

        try {
            System.out.println(Thread.currentThread().getName()+"写入"+key);
            map.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入完毕");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }

    }

    //取，读。读的时候无所谓，多个线程一起读都行
    public void get(String key){
        readWriteLock.readLock().lock();

        try {
            System.out.println(Thread.currentThread().getName()+"读取"+key);
            String s = map.get(key);
            System.out.println(Thread.currentThread().getName()+"成功取出");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }



    }


}